#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;

class Singleton{
public:
    static Singleton* getInstance(){
        pthread_once(&_once_control, init);
        return _pInstance;
    }

    void print() { cout << "Singleton working" << endl; }   // 示例方法

private:
    static Singleton *_pInstance;
    static pthread_once_t _once_control;

    // 构造与析构函数
    Singleton() = default;  // 只定义不实现会报错
    ~Singleton() = default;

    static void init(){
        if(_pInstance == nullptr){
            _pInstance = new Singleton();
            cout << "getInstance" << endl;
        }
        atexit(destroy);    // 不要理会这个报错
    }

    static void destroy(){
        if(_pInstance != nullptr){
            delete _pInstance;
            _pInstance = nullptr;
            cout << "destroy" << endl;
        }
    }

    // 删除非单例函数
    Singleton(const Singleton&) = delete;
    Singleton operator=(const Singleton&) = delete;
};

// 初始化静态成员
Singleton* Singleton::_pInstance = nullptr;
pthread_once_t Singleton::_once_control = PTHREAD_ONCE_INIT;

void test(){
    Singleton::getInstance()->print();
    Singleton::getInstance()->print();

//    AutoRelease ar(Singleton::getInstance());
}

int main()
{
    test();
    return 0;
}

